package leetcode.linkedList.p203;

/**
 * 
 * @Title: Solution203.java 
 * @Package leetcode 
 * @Description: 问题203：移除链表元素，使用递归方式实现
 *                      在控制台中打印提示，方便更好地理解递归
 * @author CandyWall   
 * @date 2021年1月4日 上午12:27:20 
 * @version V1.0
 */
/**
 * Definition for singly-linked list. public class ListNode { int val; ListNode
 * next; ListNode(int x) { val = x; } }
 */
public class Solution203_v6_recursiveImpl {
	public ListNode removeElements(ListNode head, int val, int depth) {
	    String depthStr = generateDepthStr(depth);
	    System.out.println(depthStr + "Call: remove " + val + " in " + head);
        //如果表头为空
        if(head == null) {
            System.out.println(depthStr + "Return: " + head);
            return head;
        }
        //递归调用
        ListNode res = removeElements(head.next, val, depth + 1);
        System.out.println(depthStr + "After remove: " + res);
        ListNode ret;
        if(head.val == val) {
            ret = res;
        } else {
            head.next = res;
            ret = head;
        }
        System.out.println(depthStr + "Return: " + ret);
        return ret;
	}

    private String generateDepthStr(int depth) {
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < depth; i++) {
            sb.append("--");
        }
        return sb.toString();
    }

    public static void main(String[] args) {
		ListNode node = new ListNode(1);
		ListNode p = node;
		p.next = new ListNode(2);
		p = p.next;
		p.next = new ListNode(6);
		p = p.next;
		p.next = new ListNode(3);
		p = p.next;
		p.next = new ListNode(4);
		p = p.next;
		p.next = new ListNode(5);
		p = p.next;
		p.next = new ListNode(6);
		p = p.next;
		
		for(p = node; p != null; p = p.next) {
			System.out.print(p.val + "->");
		}
		System.out.println();
		node = new Solution203_v6_recursiveImpl().removeElements(node, 6, 0);
		for(p = node; p != null; p = p.next) {
			System.out.print(p.val + "->");
		}
		/*ListNode p = node;
		for(p = node; p != null;p = p.next) {
			System.out.print(p.val + "->");
		}
		System.out.println();
		node = new Solution203_v1().removeElements(node, 1);
		for(p = node; p != null;p = p.next) {
			System.out.print(p.val + "->");
		}*/
	}
}


